package com.wl.api.controller.system;

import java.util.Objects;
import java.util.function.Predicate;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wl.api.common.utils.BeanUtils;
import com.wl.api.common.utils.ErrorCodeEnum;
import com.wl.api.common.utils.JsonObject;
import com.wl.api.common.utils.StringUtil;
import com.wl.api.common.utils.constant.ClientConstant;
import com.wl.api.controller.base.CommonController;
import com.wl.api.dto.base.CommonUserDTO;
import com.wl.api.dto.system.SecurityChannelAreaServiceDTO;
import com.wl.api.model.system.SecurityChannelAreaService;
import com.wl.api.model.system.SecurityChannelAreaServiceNetwork;
import com.wl.api.model.system.SecurityChannelAreaServicePartner;
import com.wl.api.service.system.ISecurityChannelAreaServiceNetworkService;
import com.wl.api.service.system.ISecurityChannelAreaServicePartnerService;
import com.wl.api.service.system.ISecurityChannelAreaServiceService;
import com.wl.api.service.system.ISecurityChannelService;

/**
 * 
 * @author cj desc 区域服务定义 区域ID --> 区域服务类型(feePickup上门取件费, selfDelivery 自送网点 )
 *         --> 上门取件服务合作者--> 价格阶梯 --> 自送网点地址 --> 价格阶梯
 * 
 */
@RestController
@RequestMapping("/admin/area/service/")
public class AdminAreaServiceController extends CommonController {

	@Autowired
	ISecurityChannelAreaServiceService channelAreaServiceService;
	@Autowired
	ISecurityChannelAreaServiceNetworkService channelAreaServiceNetworkService;
	@Autowired
	ISecurityChannelAreaServicePartnerService channelAreaServicePartnerService;

	@Autowired
	ISecurityChannelService channelService;

	/***
	 * 定义区域服务类型定义
	 * 
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/manage", method = RequestMethod.POST)
	public JsonObject create(@RequestBody SecurityChannelAreaServiceDTO param) throws Exception {
		JsonObject json = JsonObject.getInstance();
		boolean pass = true;
		String title = "", code = "";
		if (validate().or(s -> s.getServiceId() != null).test(param)) {
			title = ErrorCodeEnum.param_error.getMessage();
			code = ErrorCodeEnum.param_error.getError_code();
			pass = false;
		}
		if (pass) {
			init(param);
			SecurityChannelAreaService entity = BeanUtils.copyProperties(param, SecurityChannelAreaService.class);
			channelAreaServiceService.insert(entity);
			json.setData(entity.getServiceId());
		}
		setJsonMessage(json, title, code, pass);
		return json;
	}

	/**
	 * 修改数据
	 * 
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/manage", method = RequestMethod.PUT)
	public JsonObject modify(@RequestBody SecurityChannelAreaServiceDTO param) throws Exception {
		JsonObject json = JsonObject.getInstance();
		boolean pass = true;
		String title = "", error_code = "";
		if (validate().or(s -> s.getServiceId() == null).test(param)) {
			title = ErrorCodeEnum.param_error.getMessage();
			error_code = ErrorCodeEnum.param_error.getError_code();
			pass = false;
		}
		if (pass) {
			channelAreaServiceService.updateById(BeanUtils.copyProperties(param, SecurityChannelAreaService.class));
			json.setData(param.getServiceId());
		}
		setJsonMessage(json, title, error_code, pass);
		return json;
	}

	/** 只提供修改数据状态 */
	@RequestMapping(value = "/manage/{id}/{status}", method = RequestMethod.PUT)
	public JsonObject modifyStatus(@PathVariable("id") Integer id, @Param("status") Integer status) throws Exception {
		JsonObject json = JsonObject.getInstance();
		getCommonUser();
		channelAreaServiceService.updateById(SecurityChannelAreaService.builder().status(status).serviceId(id).build());
		setJsonMessage(json);
		return json;
	}

	@RequestMapping(value = "/manage/{id}", method = RequestMethod.DELETE)
	public JsonObject del(@PathVariable("id") Integer id) throws Exception {
		JsonObject json = JsonObject.getInstance();
		boolean pass = true;
		String title = "", error_code = "";
		getCommonUser();

		if (channelAreaServiceNetworkService
				.selectCount(new EntityWrapper<SecurityChannelAreaServiceNetwork>().where("service_id={0}", id)) > 0
				&& channelAreaServicePartnerService.selectCount(
						new EntityWrapper<SecurityChannelAreaServicePartner>().where("service_id={0}", id)) > 0) {
			pass = false;
			title = ErrorCodeEnum.bad_request_data_used.getMessage();
			error_code = ErrorCodeEnum.bad_request_data_used.getError_code();
		}
		if (pass) {
			channelAreaServiceService.deleteById(id);
		}
		setJsonMessage(json, title, error_code, pass);
		return json;
	}

	@RequestMapping(value = "/manage/{id}", method = RequestMethod.GET)
	public JsonObject getDetail(@PathVariable("id") Integer id) throws Exception {
		getCommonUser();
		JsonObject json = JsonObject.getInstance();
		json.setData(channelAreaServiceService.selectById(id));
		setJsonMessage(json);
		return json;
	}

	@RequestMapping(value = "/manage", method = RequestMethod.GET)
	public JsonObject getItemList(SecurityChannelAreaServiceDTO param) throws Exception {
		JsonObject json = JsonObject.getInstance();
		getCommonUser();
		param.buildStartTime(param.getStartTime()).buildEndTime(param.getEndTime()).buildPage(param.getPage(),
				param.getPageSize());
		json.setData(channelAreaServiceService.selectList(new EntityWrapper<SecurityChannelAreaService>(
				BeanUtils.copyProperties(param, SecurityChannelAreaService.class))));
		setJsonMessage(json);
		return json;
	}

	private void init(SecurityChannelAreaServiceDTO param) throws Exception {
		CommonUserDTO user = getCommonUser();
		if (Objects.isNull(param.getStatus())) {
			param.setStatus(1);
		}
		param.buildCreateMsg(user.getId(), user.getUsername());
	}

	private Predicate<SecurityChannelAreaServiceDTO> validate() {
		/*
		 * return s -> StringUtil.isEmpty(s.getName()) ||
		 * StringUtil.isEmpty(s.getLogoImg()) || StringUtil.isEmpty(s.getChannelDesc())
		 * || ObjectUtil.isEmpty(s.getCostTimeFrom()) ||
		 * ObjectUtil.isEmpty(s.getReachAreaId()) ||
		 * ObjectUtil.isEmpty(s.getFromAreaId()) ||
		 * ObjectUtil.isEmpty(s.getCostTimeTo()) ||
		 * CollectionUtil.isEmpty(s.getFeeLadderList()) ||
		 * s.getFeeLadderList().parallelStream().anyMatch(a ->
		 * ObjectUtil.isEmpty(a.getAmount()) || ObjectUtil.isEmpty(a.getWeightFrom()) ||
		 * ObjectUtil.isEmpty(a.getWeightTo()));
		 */
		return s -> StringUtil.isEmpty(s.getServiceName()) || Objects.isNull(s.getAreaId())
				|| StringUtil.isEmpty(s.getServiceDesc()) || StringUtil.isEmpty(s.getFeeType())
				|| !Objects.equals(s.getFeeType(), ClientConstant.FEE_TYPE_PICK_UP)
						&& !Objects.equals(s.getFeeType(), ClientConstant.fee_type_seft_delivery);
	}

}
